package com.tsd.core.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @ClassName: AspectUtil
 * @Description: TODO
 * @Author: Hillpool
 * @Date: 2024/4/22 16:05
 * @Version: 1.0
 */
public class AspectUtil {

    /**
     * 获取注解
     *
     * @param joinPoint
     * @return
     */
    public static <T extends Annotation> T getAannotation(ProceedingJoinPoint joinPoint, Class<T> clazz) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        if (null == method) {
            return null;
        }
        return method.getAnnotation(clazz);
    }

    /**
     * 获取请求路径
     *
     * @param joinPoint
     * @return
     */
    public static String getRequestURL(ProceedingJoinPoint joinPoint) {
        RequestMapping requestMapping = getAannotation(joinPoint, RequestMapping.class);
        if (requestMapping != null) {
            String[] path = requestMapping.value();
            if (path.length > 0) {
                return path[0];
            }
            path = requestMapping.path();
            if (path.length > 0) {
                return path[0];
            }
        }
        PostMapping postMapping = getAannotation(joinPoint, PostMapping.class);
        if (postMapping != null) {
            String[] path = postMapping.value();
            if (path.length > 0) {
                return path[0];
            }
            path = postMapping.path();
            if (path.length > 0) {
                return path[0];
            }
        }
        GetMapping getMapping = getAannotation(joinPoint, GetMapping.class);
        if (getMapping != null) {
            String[] path = getMapping.value();
            if (path.length > 0) {
                return path[0];
            }
            path = getMapping.path();
            if (path.length > 0) {
                return path[0];
            }
        }
        return null;
    }
}
